﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <link rel="stylesheet" type="text/css" href="/Resources/easyui-1.32/themes/default/easyui.css" />
    <link rel="stylesheet" type="text/css" href="/Resources/easyui-1.32/themes/icon.css" />
    <style type="text/css">
        .lockrow
        {
            background-color: #d8f2ea;
        }
        .lockcol
        {
            background-color: #d8f2ea;
        }
        .selected
        {
            background-color: #d8f2ea;
        }
        .error
        {
            background-color: #FF0000;
            color: White;
        }
        
        .modified
        {
            background-color: #00ff90;
        }
    </style>
    <script type="text/javascript" src="/Resources/easyui-1.32/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="/Resources/easyui-1.32/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="/Resources/JSON-js-master/json2.js"></script>
    <script type="text/javascript" src="/Resources/xiaovcn/scripts/usercheck.js"></script>
    <script type="text/javascript" src="/Resources/xiaovcn/scripts/easyuigrid-ext.js"></script>
    <script type="text/javascript">

        var lockall = false;
        var lockrow = "#DataGrid_LockRow#";
        var lockcolumn = "#DataGrid_LockColumn#";
        var hiddencolumn="#DataGrid_HiddenColumn#";
        var hiddenrow="#DataGrid_HiddenRow#";
        var lockcell = "#DataGrid_LockCell#"; //startcol,endcol,startrow,endrow|startcol,endcol,startrow,endrow
        var colwidth = "#DataGrid_ColWidth#";
        //var hc = "#DataGrid_HC#";
        var hc="4,5";
        var itypestring="#DataGrid_ColumnType#";
        var itypes = itypestring.split('|');
        var selectedcellid;
        var selectedcolindex;
        var selectedrowindex;
        var rowscount; //当前表格行数
        var tname="#DataGrid_Tn#";        
        var saveSuccessed=false;

        function getUrlParam(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }

        $(document).ready(function () {
            var lastIndex;//new
            $('#tt').datagrid({
                url: '#DataGrid_Url#',
                title: '#DataGrid_Title#', rownumbers: true,height: userScreenHeight, fitColumns: false, singleSelect: true, striped: true,
                
                columns:
                [
                    #DataGrid_Column#
                ],
                toolbar: [{
                    text: '新增行',
                    iconCls: 'icon-add',              
                    disabled:#DataGrid_ToolBar_InsertRow#,
                    handler: function () {
                        var a1= $('#dwbm').val();
                        var a2 = $('#year').val();
                        var a3= $('#month').val();
                        InsertRow('#DataGrid_Tn#',a1,a2,a3);                     
                    }
                },'-',{
                text: '新增子节点',
                iconCls: 'icon-add',        
                disabled:#DataGrid_ToolBar_InsertChild#,
                handler: function () {
                    var node = $('#tt').datagrid('getSelected');   
                    if(node)
                    {
                        InsertChild('#DataGrid_Tn#',node.NF,node.YF,node.DWBM,node.ZBBM,node.CJ);                     
                    }
                    else
                    {
                        alert('请选中一行，再点击增加子节点');
                    }
                    }
                },'-',{
                    text: '删除行',
                    iconCls: 'icon-remove',        
                    disabled:#DataGrid_ToolBar_Delete#,
                    handler: function () {
                        var node = $('#tt').datagrid('getSelected');   
                        if (node) {
                            if(confirm('确定要删除吗？'))
                            {
                                DeleteRow('#DataGrid_Tn#',node.ROWID,node.ZBBM,node.NF,node.YF,node.DWBM);
                            }
                        }
                        else {
                            alert('请选择一行');
                        }
                    }
                },'-',{
                    text: '保存',
                    iconCls: 'icon-save',                    
                    disabled:#DataGrid_ToolBar_Save#,
                    handler: function () {
                        //$('#tt').datagrid('acceptChanges');
                        SaveData();  
                                             
                    }
                },'-',{
                    text: '清空',
                    iconCls: 'icon-cancel',             
                    disabled:#DataGrid_ToolBar_Clear#,
                    handler: function () {
                        if(confirm('确定要清空并重建本表数据吗？'))
                        {
                            var a1= $('#dwbm').val();
                            var a2 = $('#year').val();
                            var a3= $('#month').val();
                            ClearReport('#DataGrid_Tn#',a1,a2,a3);                        
                        }
                    }
                },'-',{
                    text: '表内计算',
                    iconCls: 'icon-reload', 
                    disabled:#DataGrid_ToolBar_Compute#,
                    handler: function () {
                        if(confirm('确定要计算本表数据吗？'))
                        {
                            var a1= $('#dwbm').val();
                            var a2 = $('#year').val();
                            var a3= $('#month').val();
                            Compute('#DataGrid_Tn#',a1,a2,a3);          
                        }
                    }
                },'-',{
                    text: '表间提取',
                    iconCls: 'icon-reload',             
                    disabled:#DataGrid_ToolBar_Featch#,                    
                    handler: function () {
                        if(confirm('确定要从其他表提取数据吗？'))
                        {
                            var a1= $('#dwbm').val();
                            var a2 = $('#year').val();
                            var a3= $('#month').val();
                            Featch('#DataGrid_Tn#',a1,a2,a3);          
                        }
                    }
                },'-',{
                    text: '分级汇总',
                    iconCls: 'icon-sum',          
                    disabled:#DataGrid_ToolBar_Sum#,     
                    handler: function () {
                        if(confirm('确定要汇总本表数据吗？'))
                        {
                            var a1= $('#dwbm').val();
                            var a2 = $('#year').val();
                            var a3= $('#month').val();
                            Sum('#DataGrid_Tn#',a1,a2,a3);          
                        }
                    }
                },'-',{
                    text: '继承',
                    iconCls: 'icon-redo',         
                    disabled:#DataGrid_ToolBar_Carry#,     
                    handler: function () {
                        if(confirm('注意：将会覆盖本表数据，不可恢复，确定要拷贝上一次的数据吗？'))
                        {
                            var a1= $('#dwbm').val();
                            var a2 = $('#year').val();
                            var a3= $('#month').val();
                            Carryon('#DataGrid_Tn#',a1,a2,a3,'#DataGrid_LastYear#','#DataGrid_LastMonth#');          
                        }
                       //window.open("exportxls.aspx?tn=#DataGrid_Tn#&dwbm="+a1+"&year="+a2+"&month="+a3+"",'blank');
                    }
                }
                ],
                onBeforeLoad: function () {
                    //$(this).datagrid('rejectChanges');
                },
                onClickCell: function (index, field, value) {
                    if (!islock_by_index_field(index, field)) {
                        selectedcellid = getId_by_index_field(index, field);
                        selectedcolindex = get_colindex_byfield(field);
                        selectedrowindex = index;
                        //alert("colindex:"+selectedcolindex+"/rowlindex:"+selectedrowindex);
                        switchtdinput($("#" + selectedcellid));
                    }
                },
                onLoadSuccess: function (val) {
                    SetColumnDataType(); //数据类型
                    GetRowsCount(); //更新行数
                    setCJ();           //指标层级  
                    HiddenC();    //隐藏Column
                    LockC();          //锁定Column
                   // LockR();          //锁定Row
                    //LockA();         //锁定区域   
                    HiddenR();    //隐藏Row
                    //MergeCell(); //合并Cell
                    //SetStyle();     //设定列宽  性能待优化
                },
            });
        });

        function GetRowsCount(){
            rowscount=$('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr').length;
        }

        function ReloadGrid()
        {
            $('#tt').datagrid('reload');
        }

        function MergeCell(){
            //只有下列表合并单元格 
            if(tname=="NH67" || tname=="NH67_ALL")
            {
                mergeCellsByField('tt','ZBMC');
            }
        }

        function Exportxls(tn,dwbm,year,month)
        {
            $.ajax({
                type: 'post',
                url: '/PluginSrc/StatisticalSystem/ExportXls.aspx',
                data: { tn: tn,year:year,month:month,dwbm:dwbm },
                datatype: 'html',
                success: function (result) {  },
                error: function (result) { alert(result.responseText); },
            });  
        }

        function Compute(tn,dwbm,year,month)
        {
            $.ajax({
                type: 'post',
                url: '/PluginSrc/StatisticalSystem/Compute.aspx',
                data: { tn: tn,year:year,month:month,dwbm:dwbm },
                datatype: 'text',
                success: function (result) { ReloadGrid();showmsger('计算完成');  },
                error: function (result) { alert(result.responseText); },
            });  
        }
       
        //异步调用更新
        function AjaxAutoCompute(obj)
        {           
            
            var zd= $(obj).parent().attr("field");   //获取当前更新的字段
            var row = $(obj).parent().parent()[0].id;
            var r=row.substring(row.lastIndexOf('-')+1);                     
            var zbbm =get_zbbm_byrowindex(r);           
            //alert(r);
            var tn='#DataGrid_Tn#';
            var dwbm= $('#dwbm').val();
            var year = $('#year').val();
            var month= $('#month').val();
            $.ajax({
                type: 'post',
                url: '/PluginSrc/StatisticalSystem/AjaxAutoCompute.aspx',
                data: { tn: tn,year:year,month:month,dwbm:dwbm,zbbm:zbbm,zd:zd },
                datatype: 'json',
                success: function (result)
                {       
                    //Hack:自动调用计算性能测试 2013-1-14 by pengwei
                    //返回值处理 {"Zbbm":"CL00070008","Zd":"COL4","Value":"200","Bbbm":"CL0001","Dwbm":"HB01","Nf":2014,"Yf":1},{....}
                    var json = JSON.parse(result);
                    //alert(JSON.stringify(json));
                    for(var i=0;i<json.length;i++){
                        var rzbbm = json[i].Zbbm;                        
                        var rzd = json[i].Zd;
                        var rval = json[i].Value;
                        var rc = get_colindex_byfield(rzd);
                        var rr = get_rowindex_byzbbm(rzbbm);
                        //设置值
                        if(rc>=0&&rr>=0){
                            get_cell_selector_byindex(rr,rc).text(rval);
                            showmsger('自动计算表内公式'+rr+'.'+rc+'.'+rval+'.');
                        }
                        //alert(rc+':'+rr+':'+rval);
                    }
                    //showmsger('自动计算表内公式'); 
                },
                error: function (result) {
                    alert(result.responseText);
                },
            });  
        }

        function Sum(tn,dwbm,year,month)
        {
            $.ajax({
                type: 'post',
                url: '/PluginSrc/StatisticalSystem/Sum.aspx',
                data: { tn: tn,year:year,month:month,dwbm:dwbm },
                datatype: 'text',
                success: function (result) { ReloadGrid();showmsger('汇总完成'); },
                error: function (result) { alert(result.responseText); },
            });  
        }

        function Carryon(tn,dwbm,year,month,preyear,premonth)
        {
            $.ajax({
                type: 'post',
                url: '/PluginSrc/StatisticalSystem/CarryOn.aspx',
                data: { tn: tn,year:year,month:month,dwbm:dwbm,preyear:preyear,premonth:premonth },
                datatype: 'text',
                success: function (result) { ReloadGrid();showmsger('复制上次数据完成');  },
                error: function (result) { alert(result.responseText); },
            });  
        }
        function Featch(tn,dwbm,year,month)
        {
            $.ajax({
                type: 'post',
                url: '/PluginSrc/StatisticalSystem/Featch.aspx',
                data: { tn: tn,year:year,month:month,dwbm:dwbm },
                datatype: 'text',
                success: function (result) { ReloadGrid();showmsger('提取完成'); },
                error: function (result) { alert(result.responseText); },
            });  
        }
        function LockReport(tn,dwbm,year,month)
        {
            $.ajax({
                type: 'post',
                url: '/PluginSrc/StatisticalSystem/Report.aspx',
                data: { tn: tn,year:year,month:month,dwbm:dwbm },
                datatype: 'text',
                success: function (result) { ReloadGrid();alert('上报成功'); },
                error: function (result) { alert(result.responseText); },
            });  
        }

        function ClearReport(tn,dwbm,year,month)
        {
            $.ajax({
                type: 'post',
                url: '/PluginSrc/StatisticalSystem/ClearReport.aspx',
                data: { tn: tn,year:year,month:month,dwbm:dwbm },
                datatype: 'text',
                success: function (result) { ReloadGrid();showmsger('数据已清空'); },
                error: function (result) { alert(result.responseText); },
            });  
        }

        function DeleteRow(tn,rowid,zbbm,year,month,dwbm){
            SaveData();//先保存数据
            $.ajax({
                type: 'post',
                url: '/PluginSrc/StatisticalSystem/DeleteRow.aspx',
                data: { rowid: rowid ,tn:tn,zbbm:zbbm,year:year,month:month,dwbm:dwbm},
                datatype: 'html',
                success: function (result) { ReloadGrid(); },
                error: function (result) { alert(result.responseText); },
            });     
        }

        function InsertRow(tn,dwbm,year,month)
        {
            SaveData();//先保存数据
            $.ajax({
                type: 'post',
                url: '/PluginSrc/StatisticalSystem/InsertRow.aspx',
                data: { tn: tn,year:year,month:month,dwbm:dwbm },
                datatype: 'text',
                success: function (result) { ReloadGrid();},
                error: function (result) { alert(result.responseText); },
            });        
        }

        function InsertChild(tn,year,month,dwbm,zbbm,cj)
        {
            SaveData();//先保存数据
            $.ajax({
                type: 'post',
                url: '/PluginSrc/StatisticalSystem/InsertChild.aspx',
                data: { tn: tn,year:year,month:month,dwbm:dwbm,zbbm:zbbm,cj:cj },
                datatype: 'text',
                success: function (result) {ReloadGrid(); },
                error: function (result) { alert(result.responseText); },
            });        
        }

        function UpdateTBSJ(tn,year,month,dwbm)
        {            
            $.ajax({
                type: 'post',
                url: '/PluginSrc/StatisticalSystem/UpdateTbsj.aspx',
                data: { tn: tn,year:year,month:month,dwbm:dwbm},
                datatype: 'text',
                success: function (result) {},
                error: function (result) { alert(result.responseText); },
            });        
        }

        //更新数据
        function SaveData() {       
            var dwbm= $('#dwbm').val();
            var year = $('#year').val();
            var month= $('#month').val();
            var errorcount = $('.error').length;
            UpdateTBSJ('#DataGrid_Tn#',year,month,dwbm);
            if (errorcount > 0) {
                alert('输入数据错误,请检查');
            }
            else {
                //更新数据   
                var r = $("tr[changed='1']").length;
                if(r>0)
                {
                    var xml = "<DataRoot>";
                    for (var i = 0; i < r; i++) {
                        xml += "<Record>";
                        var c = $("tr[changed='1']:eq(" + i + ") td").length;
                        for (var j = 0; j < c; j++) {
                            var fd = $("tr[changed='1']:eq(" + i + ") td:eq(" + j + ") ").attr("field");
                            xml += "<" + fd + ">"
                            xml += $("tr[changed='1']:eq(" + i + ") td:eq(" + j + ") ").text();
                            xml += "</" + fd + ">";
                        }
                        xml += "</Record>";
                    }
                    xml += "</DataRoot>";
                    //alert(xml);
                    //提交到数据库                     
                    $.ajax({
                        type: 'post',
                        url: '/PluginSrc/StatisticalSystem/SaveData.aspx',
                        data: { data: encodeURIComponent(xml), tn: '#DataGrid_Tn#' ,year:year,month:month,dwbm:dwbm},
                        datatype: 'html',
                        success: function (result) {    
                            ReloadGrid();                                                    
                            showmsger('数据保存成功');},
                        error:function (result) { saveSuccessed=false;alert(result.responseText); },
                    });       
                    
                }
                
            }
               
        }

        function HiddenC(){
            if (hiddencolumn != "NULL" && hiddencolumn != "") {
                var str = hiddencolumn.split(',');
                for (var i = 0; i < str.length; i++) {
                    var f = $('#datagrid-row-r1-2-0 td:eq(' + str[i] + ')').attr("field");
                    $('#tt').datagrid('hideColumn',f);
                }
               
               
            }
        }

        function HiddenR(){
            if (hiddenrow != "NULL" && hiddenrow != "") {
                var str = hiddenrow.split(',');
                for (var i = 0; i < str.length; i++) {
                    $('#datagrid-row-r1-1-'+str[i]).hide();     
                    $('#datagrid-row-r1-2-'+str[i]).hide();     
                }
            }
        }

        function SetStyle() {
            if (colwidth != "NULL" && colwidth != "") {
                var str = colwidth.split('|');
                for (var i = 0; i < str.length; i++) {
                    var m = str[i].split(',');
                    var col = m[0];
                    var width = m[1];
                    var f = $('#datagrid-row-r1-2-0 td:eq(' + col + ')').attr("field");
                    if (f) {
                        //$('#tt').datagrid('autoSizeColumn',f); //此处明显降低性能耗时，待优化
                    }
                }
            }
        }

        function SetColumnDataType(){      

            //列的数据类型
            var str= itypestring.split('|');           

            var c = $('#datagrid-row-r1-2-0 td[field]');
            
            for (var j = 0; j < c.length; j++) {
                $('#datagrid-row-r1-2-0 td[field]:eq('+j+')').attr('itype',str[j]);                
            }

        }

        function LockA() {
            //lock Area 起始列 终止列 起始行 终止行
            if (lockcell != "NULL" && lockcell != "") {
                var str = lockcell.split('|');
                for (var i = 0; i < str.length; i++) {
                    xy = str[i].split(',');
                    var x = Number(xy[0]);
                    var xspan = Number(xy[1]);
                    var y = Number(xy[2]);
                    var yspan = Number(xy[3]);
                    for (var t = y; t <= yspan; t++) {
                        for (var j = x ; j <= xspan; j++) {
                            var q = $('#datagrid-row-r1-2-' + t + " td:eq(" + j + ")");
                            q.attr("lock", "1");
                            q.addClass("selected");
                        }
                    }
                }
            }
        }

        function LockC() {
            if (lockcolumn != "NULL"&&lockcolumn != "") {
                var rows = $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr').length;
                var str = lockcolumn.split(',');
                for (var j = 0; j < str.length; j++) {
                    for (var i = 0; i < rows; i++) {
                        $('#datagrid-row-r1-2-' + i + " td:eq(" + str[j] + ")").attr("lock", "1");
                        $('#datagrid-row-r1-2-' + i + " td:eq(" + str[j] + ")").addClass("lockcol");
                    }
                }
            }
            if (hiddencolumn != "NULL"&&hiddencolumn != "") {
                var rows = $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr').length;
                var str = hiddencolumn.split(',');
                for (var j = 0; j < str.length; j++) {
                    for (var i = 0; i < rows; i++) {
                        $('#datagrid-row-r1-2-' + i + " td:eq(" + str[j] + ")").attr("lock", "1");
                        $('#datagrid-row-r1-2-' + i + " td:eq(" + str[j] + ")").addClass("lockcol");
                    }
                }
            }
        }

        function LockR() {
            //$('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(0)').addClass('lockrow');
            if (lockrow != "NULL") {
                var rows = lockrow.split(',');
                for (var i = 0; i < rows.length; i++) {
                    $('#datagrid-row-r1-2-' + rows[i] + " td").attr("lock", "1");
                    $('#datagrid-row-r1-2-' + rows[i] + " td").addClass("lockrow");
                }
            }
        }

        function getId_by_index_field(index, field) {
            var id = "datagrid-row-r1-2-" + index + " td[field='" + field + "'] div";
            //$("#"+id).addClass("selected");
            //var rowposition="datagrid-row-r1-2-"+index;
            return id;
        }

        

        //根据index和field判定单元格是否锁定
        function islock_by_index_field(index, field) {
            var r = $("#datagrid-row-r1-2-" + index + " td[field='" + field + "']").attr("lock");
            if (r == "1")
                return true;
            else
                return false;
        }

        //根据行索引和列索引判定是否锁定
        function islock_by_index(rindex, cindex) {
            var r = $("#datagrid-row-r1-2-" + rindex + " td:eq(" + cindex + ")").attr("lock");
            if (r == "1")
                return true;
            else
                return false;
        }

        var pre = null;
        var inputfomate = "<input type='text' style='padding:0px;'/>";
        var tdinputselection = "";
        var cellislock = "0";

        //Chorme
        var EventUtil ;
        ChormeOnPaste();        
        function ChormeOnPaste()
        {
            if (navigator.userAgent.indexOf("MSIE") == -1)
            {
                EventUtil = {
                    addHandler: function (element, type, handler) {
                        if (element.addEventListener) {
                            element.addEventListener(type, handler, false);
                        } else if (element.attachEvent) {
                            element.attachEvent("on" + type, handler);
                        } else {
                            element["on" + type] = handler;
                        }
                    },
                    getEvent: function (event) {
                        return event ? event : window.event;
                    },
                    getClipboardText: function (event) {
                        var clipboardData = (event.clipboardData || window.clipboardData);
                        return clipboardData.getData("text");
                    },
                    setClipboardText: function (event, value) {
                        if (event.clipboardData) {
                            return event.clipboardData.setData("text/plain", value);
                        } else if (window.clipboardData) {
                            return window.clipboardData.setData("text", value);
                        }
                    },
                    preventDefault: function (event) {
                        if (event.preventDefault) {
                            event.preventDefault();
                        } else {
                            event.returnValue = false;
                        }
                    }
                };
            }
        }
        
        

        //IE

        function switchtdinput(obj) {
            
            if (pre) {
                doinpleave(pre);               
            }  
            
            var width = $(obj).width() * 1.0;
            var objtxt = $.trim($(obj).text());
            $(obj).html($(inputfomate).val(objtxt));
            
            pre = $(obj).find('input').css("border", "1px solid red").width(width)[0];
            $(obj).find('input').trigger("focus").trigger("select");
            //$(obj).find('input').css("class","easyui-validatebox");
            $(obj).find('input').click(function (event) {
                stopevent(event);
                return false;
            }).blur(function (event) {
                inpleave(event, this);
                //alert(1);
            }).keypress(function (event) {
                stopevent(event);
            }).keyup(function (event) {
                return setpreornext(event, this);
            }).keydown(function (event) {
                tdinputselection = getSelectedText();
                stopevent(event);
                if (event.ctrlKey && event.keyCode == 86) {
                    var clipText;
                    if (!(!!window.ActiveXObject || "ActiveXObject" in window))
                    {                        
                        alert("您的浏览器不支持从剪贴板读取数据,请手工复制文本框中内容");
                    }
                    else
                    {
                        //从剪贴板粘贴数据 =========== by xiaovcn
                        clipText = window.clipboardData.getData('Text');
                        
                    }
                    if (clipText != null) {
                        //去除末尾的\r\n以免出现空值 从excel复制默认总是有一个回车 原因?
                        var p = clipText.lastIndexOf(String.fromCharCode(13) + String.fromCharCode(10));
                        if (p != -1) {
                            clipText = clipText.substring(0, p);
                        }
                        //用\r\n分割数据串
                        clipRows = clipText.split(String.fromCharCode(13) + String.fromCharCode(10));

                        for (i = 0; i < clipRows.length; i++) {
                            //用\t分割数据
                            clipRows[i] = clipRows[i].split(String.fromCharCode(9));
                        }
                        //写入html
                        paste(event, this, clipRows);
                    }
                    //从剪贴板粘贴数据 ===========end by xiaovcn
                }
            });

        }

        

        //根据field获取当前的列索引 
        function get_colindex_byfield(field) {
            var c = "[field='" + field + "']"
            var s = $('#datagrid-row-r1-2-0 td' + c).index();
            return s;
        }

        //根据id返回行索引
        function get_rowindex_byid(obj) {
            return obj.substring(selectedcellid.lastIndexOf('-') + 1)
        }

        //根据指标编码返回行索引
        var zbbmindex=[#DataGrid_ZBBMIndex#]; 
        function get_rowindex_byzbbm(z){            
            var index=-1;
            for(var i=0;i<zbbmindex.length;i++)
            {
                //计算zbbm所在的位置
                if(zbbmindex[i].name==z)
                    index=i;
                break;
            }
            return index;
            
        }

        //根据行获取指标编码
        function get_zbbm_byrowindex(r){
            return $('#'+getId_by_index_field(r,'ZBBM')).text();
        }

        //根据行索引和列索引获取jquery选择器 为复制粘贴excel数据
        function get_cell_selector_byindex(r, c) {
            return $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + r + ') td:eq(' + c + ') div')
        }

        //根据行索引和列索引 设置changed=1
        function set_cell_changed(r, c) {
            $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + r + ')').attr('changed', '1');            
            $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + r + ') td:eq(' + c + ') div').attr('changed', '1');
            $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + r + ') td:eq(' + c + ') ').addClass('modified');
        }

        //根据行索引和列索引 移除changed
        function set_cell_Nochanged(r, c) {
            $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + r + ') td:eq(' + c + ') div').removeAttr('changed');
            $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + r + ') td:eq(' + c + ')').removeClass('modified');
        }

        function set_cell_NoError(r, c) {
            $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + r + ') td:eq(' + c + ') ').removeClass('error');
        }

        function set_cell_Error(r,c){
            $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + r + ') td:eq(' + c + ') ').addClass('error');
        }

        //粘贴数据
        function paste(event, obj, clipRows) {
            var rindex = selectedrowindex;
            for (i = 0; i < clipRows.length; i++) {
                var cindex = selectedcolindex;
                for (j = 0; j < clipRows[i].length; j++) {
                    //当前位置是input  其他位置 是div
                    var value = trim(clipRows[i][j]);

                    //判定当前单元格是否锁定
                    var l = false;
                    l = islock_by_index(rindex, cindex);
                    //数据合法性
                    var ck=false;
                    ck=checkvalidate(value,itypes[cindex]);
                    if (!l) {
                        //设置值  先不管合法不合法 粘完再判定
                        set_cell_NoError(rindex,cindex);
                        get_cell_selector_byindex(rindex, cindex).text(value);
                        if(!ck){
                            set_cell_Error(rindex,cindex);
                        }
                        set_cell_changed(rindex, cindex);//设置changed属性1

                        //
                    }
                    //alert(rindex+"="+cindex);
                    cindex=getNextNotHiddenColumn(rindex,cindex,itypes.length); //列索引                               
                }
                rindex=getNextNotHiddenRow(rindex,cindex,rowscount); //行索引
                //alert(rindex);
            }
        }

        function trim(str){       

            return str.replace(/(^\s*)|(\s*$)/g, "");   

        }  


        function getNextNotHiddenColumn(r,c,maxc)
        {
            //从当前列开始 找到下一个不隐藏的列 替换粘贴时的 colindex++            
            c++;
            if(c<=maxc)
            {
                if($('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + r + ') td:eq(' + c + ')').is(":hidden"))
                    c=getNextNotHiddenColumn(r,c,maxc);                         
            }
            return c;
        }

        function getNextNotHiddenRow(r,c,maxr)
        {
            //从当前开始 找到下一个不隐藏的行 替换粘贴时的 rowindex++            
            r++;
            if(r<=maxr)
            {
                if($('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + r + ') td:eq(' + c + ')').is(":hidden"))
                    r=getNextNotHiddenRow(r,c,maxr);            
            }
            return r;
        }

        function stopevent(event) {
            event.stopPropagation();
        }

        function inpleave(event, obj) {            
            stopevent(event);
            doinpleave(obj);
        }

        function doinpleave(obj) {
            if (!obj) return;
            var val = $(obj).val();
            var $par = $(obj).parent()[0];
            $($par).text(val);   //赋值         
            pre = null;  
            //SaveData();            
            //AjaxAutoCompute($par);//离开时触发保存并计算
        }

        function getSelectionStart(o) {
            if (o.createTextRange) {
                var r = document.selection.createRange().duplicate();
                r.moveEnd('character', o.value.length);
                if (r.text == '') return o.value.length
                return o.value.lastIndexOf(r.text);
            } else return o.selectionStart;
        }

        function getSelectedText() {
            if (window.getSelection) {
                return window.getSelection().toString();
            }
            else if (document.getSelection) {
                return document.getSelection();
            }
            else if (document.selection) {
                return document.selection.createRange().text;
            }
        }

        //是否为数字
        function isnum(obj) {
            if (obj == "" || obj == null)
                return true;
            else {
                // var re = /^[0-9]+.?[0-9]*$(/^-?\d+\.?\d*
                var re= /^-?\d+\.?\d*$/;
                if (!re.test(obj)) {
                    return false;
                }
                else {
                    return true;
                }
            }
        }
        //是否为字符串
        function  isstring(obj) 
        { 
            //文本框中不能含有\n\n 1 单引号: ' \n 2 双引号: \" \n 3 竖 杠: | \n 4 尖角号: < > \n\n请检查输入
            var   pattern   =   /^[^\|"'<>]*$/; 
            if   (pattern.test(obj)) 
                return true;
            else 
                return false;
        } 

        function checkvalidate(obj,itype)
        {
            var ckresult=false;
            if(itype=="System.String")
            {
                ckresult = isstring(obj);
            }            
            if(itype=="System.Decimal")
            {
                ckresult = isnum(obj);
            }
            return ckresult;
        }


        function setpreornext(event, objThis) {
            // 输入合法性检查
            var iii = get_colindex_byfield($(objThis).parent().parent().attr("field"));
            //alert(itype);
            
            $(objThis).parent().parent().parent().attr('changed', 1);            
            var inputvalue = $(objThis).val();
            //根据type字符串来决定某列是什么数据类型
            var ck = checkvalidate(inputvalue,itypes[iii]);
            if (ck) {
                //移除error错误提示样式
                $(objThis).parent().parent().removeClass("error");
                $(objThis).parent().parent().addClass("modified");
                var count = -1;
                var current;
                stopevent(event);
                var obj; //焦点移动到得位置
                //判断键盘动作keyCode 40=Down  38=UP  13=enter 37=left  39=right 9=Tab
                if (event.keyCode == 40 || event.which == 40 || event.keyCode == 38 || event.which == 38 || event.keyCode == 13 || event.which == 13 || event.keyCode == 37 || event.which == 37 || event.keyCode == 39 || event.which == 39) {

                    //当前的位置 objThis 为 单元格中的div datagrid-row-r1-2-rowindex
                    row = $(objThis).parent().parent().parent()[0].id;

                    nextrowindex = parseInt(row.substring(row.lastIndexOf('-') + 1)) + 1;

                    prerowindex = parseInt(row.substring(row.lastIndexOf('-') + 1)) - 1;

                    nextrow = row.substring(0, row.lastIndexOf('-') + 1) + nextrowindex;

                    prerow = row.substring(0, row.lastIndexOf('-') + 1) + prerowindex;

                    field = $(objThis).parent().parent().attr("field");

                    //var id="datagrid-row-r1-2-"+index+" td[field='"+field+"'] div";              

                    var downcell = "#" + nextrow + " td[field='" + field + "'] div";
                    var dc_l = "#" + nextrow + " td[field='" + field + "']";

                    var upcell = "#" + prerow + " td[field='" + field + "'] div";
                    var uc_l = "#" + prerow + " td[field='" + field + "']";

                    var thistd = "#" + row + " td[field='" + field + "']";

                    //alert(downcell);
                    //count = parseInt($(objThis).parent().data("i"));

                    var nc = null;

                    if (event.keyCode == 40 || event.which == 40) {
                        obj = $(downcell);//向下    
                        nc = $(dc_l).attr("lock");

                    } else if (event.keyCode == 38 || event.which == 38) {
                        obj = $(upcell);//向上
                        nc = $(uc_l).attr("lock");

                    } else if (event.keyCode == 13 || event.which == 13) {
                        obj = $(downcell);//回车--向下
                        nc = $(dc_l).attr("lock");

                    } else if (event.keyCode == 37 || event.which == 37) {
                        obj = $(thistd).prev("td").find("div");//向左
                        nc = $(thistd).prev("td").attr("lock");

                    } else if (event.keyCode == 39 || event.which == 39) {
                        obj = $(thistd).next("td").find("div");//向右
                        nc = $(thistd).next("td").attr("lock");
                    }
                    if (obj) {

                        //判定要移动目标是否锁定
                        if (nc == "1") {
                            cellislock = "1";
                        }
                        else {
                            cellislock = "0";
                        }
                        if (cellislock == "0") {
                            doinpleave(objThis);
                            switchtdinput(obj);
                        }
                    }                   
                }

                if (event.keyCode == 13 || event.which == 13)
                    return false;
                else
                    return true;
            }
            else {
                //输入框变色 提示
                $(objThis).parent().parent().addClass("error");
            }
            //alert(1);
        }


        function setCJ() {
            var hcstr = hc.split(',');
            if (hcstr.length == 2) {
                var r = $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr').length;
                for (var i = 0; i < r; i++) {
                    var str = "";
                    var spacenum = $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + i + ') td:eq(' + hcstr[1] + ') div').text();

                    for (var j = 0; j < spacenum - 1; j++) {
                        str += '&nbsp;&nbsp;&nbsp;';
                    };
                    var txt = str + $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + i + ') td:eq(' + hcstr[0] + ') div').text();
                    $('.datagrid-view2 .datagrid-body .datagrid-btable tbody tr:eq(' + i + ') td:eq(' + hcstr[0] + ') div').html(txt);
                }
                //
            }
        }

        function showmsger(c){
            $.messager.show({
                title:'操作提示',
                msg:c,
                timeout:2000,
                showType:'show'
            });
        }
    </script>
</head>
<body onresize="javascript:$('#tt').datagrid('resize');">
    <div style="padding-bottom: 5px; font-size: 12px;">
        单位：#Select_DWBM# 时间：#Select_Year# #Select_Month#
    </div>
    <table id="tt">
    </table>
</body>
</html>
